﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using MediaPortal.GUI.Library;
using MediaPortal.Player;
using MediaPortal.Playlists;
using MediaPortal.Dialogs;
using MediaPortal.Plugins.Trailers.Common;
using MediaPortal.Plugins.Trailers.Providers;

namespace MediaPortal.Plugins.Trailers {
  public class GUITrailers : GUIWindow {

    #region Enums

    public enum State {
      Home = 0,
      List = 1,
      Details = 2,
      Video = 3,
    }

    public enum View {
      List = 0,
      Icons = 1,
      LargeIcons = 2,
      FilmStrip = 3
    }

    #endregion

    #region SkinControlAttributes

    [SkinControlAttribute(50)]
    protected GUIFacadeControl trailerBrowser = null;

    [SkinControlAttribute(2)]
    protected GUIButtonControl btnViewAs = null;

    [SkinControlAttribute(3)]
    protected GUISortButtonControl btnSortBy = null;

    [SkinControlAttribute(4)]
    protected GUIListControl videoBrowser = null;

    [SkinControlAttribute(5)]
    protected GUIButtonControl btnRefresh = null;

    #endregion

    private struct Breadcrumb {
      public string Label;
      public string Key;
      public State State;

      public Breadcrumb(string label, string key, State state) {
        Label = label;
        Key = key;
        State = state;
      }
    }

    #region Variables

    private const int windowId = 5900;
    private const string _labelPrefix = "#MyTrailers.";
    private const string pathHome = "//HOME";
    private const string pathProvider = "//PROVIDER";

    private State _guiState = State.Home;
    private View _guiView = View.List;
    private Stack<Breadcrumb> _guiHistory = new Stack<Breadcrumb>();
    private GUIListItemTrailerComparer.SortMethod _guiSortMethod = GUIListItemTrailerComparer.SortMethod.Title;
    private bool _guiSortAsc = true;

    private TrailerData _data;
    private Trailer _selectedTrailer = null;
    private Video _selectedVideo = null;
    private VideoQuality _selectedVideoSize;

    private bool _playingTrailer = false;
    private string _guiLabelView = string.Empty;
    private string _guiLabelHeader = string.Empty;
    private int _guiLabelItemcount = 0;

    private List<GUIListItem> _listItems = new List<GUIListItem>(); // Unfiltered List
    private string _listFilter = string.Empty; // List Filter String

    #endregion

    #region GUIWindow Base Overrides

    public override bool Init() {
      TrailersPlugin.Initialize();
      _data = new TrailerData();

      SetProperty("#MyTrailers.Details.Title", " ");
      SetProperty("#MyTrailers.Details.Director", " ");
      SetProperty("#MyTrailers.Details.Genre", " ");
      SetProperty("#MyTrailers.Details.Cast", " ");
      SetProperty("#MyTrailers.Details.Studio", " ");
      SetProperty("#MyTrailers.Details.ReleaseDate", " ");
      SetProperty("#MyTrailers.Details.Year", " ");
      SetProperty("#MyTrailers.Details.Rating", " ");
      SetProperty("#MyTrailers.Details.Description", " ");
      SetProperty("#MyTrailers.Details.Poster", "");
      SetProperty("#MyTrailers.Video.Title", " ");
      SetProperty("#MyTrailers.Video.Image", "");
      SetProperty("#MyTrailers.Video.Description", " ");
      SetProperty("#MyTrailers.Video.Quality", " ");
      SetProperty("#MyTrailers.Video.Published", " ");

      return Load(GUIGraphicsContext.Skin + @"\MyTrailers.xml");
    }

    protected override void OnPageLoad() {
      Breadcrumb current;
      switch (_guiState) {
        case State.Home:
          this.showHome();
          break;
        case State.List:
          current = this._guiHistory.Pop();
          switch (current.Key) {
            case "//PROVIDER":
              this.showProvider();
              break;
            default:
              this.showIndex(current.Key);
              break;
          }
          break;
        case State.Details:
          current = this._guiHistory.Pop();
          showDetails(current.Key);
          break;
      }

      if (btnSortBy != null)
        btnSortBy.SortChanged += new SortEventHandler(OnSortChanged);

      SwitchView();
      updateGuiState();
      base.OnPageLoad();
    }

    public override int GetID {
      get {
        return windowId;
      }
      set {
        base.GetID = value;
      }
    }

    public override void OnAction(Action action) {
      //Log.Info(action.wID.ToString());
      switch (action.wID) {
        case Action.ActionType.ACTION_PREVIOUS_MENU:

          // clear the list filter if active
          // @todo: this action should move
          if (!String.IsNullOrEmpty(_listFilter)) {
            _listFilter = string.Empty;
            filterListItems();
            return;
          }

          // If we are not on the plugin's home screen
          if (_guiState != State.Home) {
            if (!cancelDownloadWorker())
              showPrevious();

            updateGuiState();
            updateGuiButtons();
          }
          else {
            GUIWindowManager.ShowPreviousWindow();
          }
          break;
        case Action.ActionType.ACTION_KEY_PRESSED:
          if (action.m_key != null && _guiState != State.Details) {
            if (((action.m_key.KeyChar >= '0') && (action.m_key.KeyChar <= '9')) ||
              action.m_key.KeyChar == '*' || action.m_key.KeyChar == '(' ||
              action.m_key.KeyChar == '#' || action.m_key.KeyChar == '§') {

              if (action.m_key.KeyChar == '*') {
                // reset the list filter string
                _listFilter = string.Empty;
              }
              else {
                // add the numeric code to the list filter string
                Char key = (char)action.m_key.KeyChar;
                _listFilter += Common.Utils.NumPadEncode(key.ToString());
              }

              filterListItems();
              return;
            }
          }
          break;
        default:
          base.OnAction(action);
          break;
      }
    }

    protected override void OnClicked(int controlId, GUIControl control, Action.ActionType actionType) {
      if (control == trailerBrowser && actionType == Action.ActionType.ACTION_SELECT_ITEM) {
        switch (_guiState) {
          // ### HOME actions
          case State.Home:
            _data.SelectProvider = trailerBrowser.SelectedListItem.Path;
            _guiLabelView = _data.Provider.ProviderName();
            showProvider();
            break;
          // ### LIST actions
          case State.List:
            if (!OnClickPrevious()) {
              string key = trailerBrowser.SelectedListItem.Path;
              if (trailerBrowser.SelectedListItem.IsFolder) {
                showIndex(key);
                _guiLabelView = trailerBrowser.SelectedListItem.Label;
              }
              else {
                showDetails(key);
              }
            }
            break;
          default:
            //default
            break;
        }
      }
      else if (control == videoBrowser && actionType == Action.ActionType.ACTION_SELECT_ITEM) {
        OnShowDialogSelectVideo();
      }
      // ### CHANGE VIEW MODE
      else if (control == btnViewAs) {
        onChangeFacadeView();
        updateGuiButtons();
        return;
      }
      // ### SHOW SORT DIALOG
      else if (control == btnSortBy) {
        OnShowDialogSortOptions();
        updateGuiButtons();
        return;
      }
      else if (control == btnRefresh) {
        if (_guiState == State.List) {
          Breadcrumb refresh = _guiHistory.Pop();
          if (refresh.Key != pathProvider)
            showIndex(refresh.Key, false);
          else
            showProvider(false);
        }
        return;
      }
      else {
        base.OnClicked(controlId, control, actionType);
      }

      updateGuiState();
    }

    #endregion

    private void showHome() {
      _guiLabelHeader = "Trailers";
      _guiState = State.Home;
      _guiHistory.Push(new Breadcrumb(_guiLabelHeader, pathHome, _guiState));
      _listItems.Clear();
      foreach (IndexItem provider in _data.GetProviders()) {
        GUIListItem item = new GUIListItem(provider.Label);
        item.Path = provider.Key;
        MediaPortal.Util.Utils.SetDefaultIcons(item);
        if (provider.Image != string.Empty)
          item.IconImageBig = provider.Image;
        _listItems.Add(item);
      }
      updateTrailerBrowser();
    }

    private void showProvider() {
      showProvider(true);
    }

    private void showProvider(bool cache) {
      Index index = _data.GetIndex(cache);
      if (_data.Cancelled)
        return;

      _guiState = State.List;
      _guiHistory.Push(new Breadcrumb(_guiLabelView, pathProvider, _guiState));
      _listItems.Clear(); // clear unfiltered list;
      addGUIListItemBack();
      foreach (IndexItem item in index) {
        addGUIListItem(item);
      }

      updateTrailerBrowser();
    }

    private void showIndex(string key) {
      showIndex(key, true);
    }

    private void showIndex(string key, bool cache) {
      Index index = _data.GetIndex(key, cache);
      if (_data.Cancelled)
        return;

      if (index == null) {
        onShowDialogNoData();
        return;
      }

      _guiState = State.List;
      _guiHistory.Push(new Breadcrumb(_guiLabelView, key, _guiState));

      _listItems.Clear();
      addGUIListItemBack();
      foreach (IndexItem item in index) {
        addGUIListItem(item);
      }
      updateTrailerBrowser();
    }

    private void showDetails(string key) {
      _selectedTrailer = _data.GetDetails(key);
      if (_data.Cancelled)
        return;

      if (_selectedTrailer == null) {
        onShowDialogNoData();
        return;
      }

      _guiState = State.Details;
      _guiHistory.Push(new Breadcrumb(_guiLabelView, key, _guiState));

      GUIControl.ClearControl(GetID, videoBrowser.GetID);

      //OnTrailerSelectedExposeLabels(_selectedTrailer);
      _guiLabelHeader = _selectedTrailer.Title;

      if (_selectedTrailer.Type == Trailer.TrailerType.Game) {
        SetProperty("#MyTrailers.Details.Label.Cast", "Platform");
        SetProperty("#MyTrailers.Details.Label.Director", "Developer");
        SetProperty("#MyTrailers.Details.Label.Studio", "Publisher");
      } else
      {
        SetProperty("#MyTrailers.Details.Label.Cast", "Cast");
        SetProperty("#MyTrailers.Details.Label.Director", "Director");
        SetProperty("#MyTrailers.Details.Label.Studio", "Studio");
      }

      SetProperty("#MyTrailers.Details.Title", _selectedTrailer.Title);
      SetProperty("#MyTrailers.Details.Director", _selectedTrailer.Director);
      SetProperty("#MyTrailers.Details.Genre", _selectedTrailer.Genres.ToString());
      SetProperty("#MyTrailers.Details.Cast", _selectedTrailer.Cast.ToString());
      SetProperty("#MyTrailers.Details.Studio", _selectedTrailer.Studio);

      if (_selectedTrailer.ReleaseDate != DateTime.MinValue)
        SetProperty("#MyTrailers.Details.ReleaseDate", _selectedTrailer.ReleaseDate.ToShortDateString());
      else
        SetProperty("#MyTrailers.Details.ReleaseDate", "Coming Soon");

      SetProperty("#MyTrailers.Details.Year", _selectedTrailer.Year.ToString());
      SetProperty("#MyTrailers.Details.Rating", _selectedTrailer.Rating);
      SetProperty("#MyTrailers.Details.Description", _selectedTrailer.Description);
      SetProperty("#MyTrailers.Details.Poster", _selectedTrailer.Poster);

      foreach (Video video in _selectedTrailer.Media) {
        GUIListItem item = new GUIListItem();
        item.Path = video.Label;
        item.Label = video.Label;
        item.IconImage = video.Thumb;
        item.ThumbnailImage = video.Thumb;
        //if (video.Duration > TimeSpan.MinValue)
        //{
        //  item.Label2 = video.Duration.ToString();
        //}
        item.AlbumInfoTag = video;
        MediaPortal.Util.Utils.SetDefaultIcons(item);
        item.OnItemSelected += new GUIListItem.ItemSelectedHandler(OnVideoSelected);
        videoBrowser.Add(item);
      }


      if (videoBrowser.Count > 0) {
        Video video = videoBrowser[0].AlbumInfoTag as Video;
        SetProperty("#MyTrailers.Video.Title", video.Label);
        SetProperty("#MyTrailers.Video.Image", video.Thumb);
        SetProperty("#MyTrailers.Video.Description", video.Description);
        SetProperty("#MyTrailers.Video.Published", video.Date.ToShortDateString());
      }

      videoBrowser.Focus = true;
    }

    private void showPrevious() {
      Breadcrumb select = _guiHistory.Pop();

      if (select.Key == pathHome)
        return;

      Breadcrumb back = _guiHistory.Pop();
      _guiState = back.State;
      switch (back.Key) {
        case pathHome:
          showHome();
          break;
        case pathProvider:
          _guiLabelView = back.Label;
          showProvider();
          selectListItemWithKey(select.Key);
          break;
        default:
          _guiLabelView = back.Label;
          showIndex(back.Key);
          selectListItemWithKey(select.Key);
          break;
      }

    }

    private bool cancelDownloadWorker() {
      return _data.CancelData();
    }

    private void addGUIListItem(IndexItem idxItem) {
      GUIListItem item = new GUIListItem(idxItem.Label);
      item.Path = idxItem.Key;
      item.IsFolder = idxItem.Folder;
      MediaPortal.Util.Utils.SetDefaultIcons(item);
      if (!idxItem.Folder) {
        // if we have data for this trailer already
        // we can use this to spice up the GUI
        if (_data.Trailers.ContainsKey(idxItem.Key)) {
          Trailer t = _data.Trailers[idxItem.Key];
          item.AlbumInfoTag = t;
          item.Label = t.Title;
          if (t.ReleaseDate != DateTime.MinValue)
            item.Label2 = t.ReleaseDate.ToShortDateString();

          item.IconImage = t.Thumb;
          item.IconImageBig = t.Poster;
          //item.ThumbnailImage = t.Poster;
          item.OnItemSelected += new GUIListItem.ItemSelectedHandler(OnItemSelected);
        }
      }
      _listItems.Add(item);
    }

    private void addGUIListItemBack() {
      GUIListItem item = new GUIListItem("..");
      item.IsFolder = true;
      MediaPortal.Util.Utils.SetDefaultIcons(item);
      _listItems.Add(item);
    }

    private void updateGuiState() {
      clearFocus();
      if (_guiState != State.Details) {

        // Refactor all of this to be more simplistic
        SetProperty("#view", _guiLabelView);
        SetProperty("#header.text", _guiLabelHeader);
        SetProperty("#header.label", _guiLabelHeader);
        if (String.IsNullOrEmpty(_listFilter))
          SetProperty("#itemcount", Util.Utils.GetObjectCountLabel(_guiLabelItemcount));
        else
          SetProperty("#itemcount", Util.Utils.GetObjectCountLabel(_guiLabelItemcount) + " (+" + (_listItems.Count - _guiLabelItemcount - 1).ToString() + " Filtered)");

        SwitchView();

        if (!trailerBrowser.Visible) {
          btnSortBy.AllocResources(); // this is needed for the sort button
          trailerBrowser.Visible = true;
        }
        trailerBrowser.Focus = true;
      }
      else {
        btnSortBy.FreeResources();
        trailerBrowser.Visible = false;
        trailerBrowser.ListView.Visible = false;
        trailerBrowser.ThumbnailView.Visible = false;
        trailerBrowser.FilmstripView.Visible = false;
        videoBrowser.Focus = true;
      }

    }

    private void updateGuiButtons() {
      if (_guiState != State.Details) {
        string labelSort = string.Empty;

        switch (_guiSortMethod) {
          case GUIListItemTrailerComparer.SortMethod.Title:
            labelSort = GUILocalizeStrings.Get(268);
            break;
          case GUIListItemTrailerComparer.SortMethod.ReleaseDate:
            //labelSort = GUILocalizeStrings.Get(104);
            labelSort = "Sort by: Release Date";
            break;
          case GUIListItemTrailerComparer.SortMethod.Year:
            labelSort = GUILocalizeStrings.Get(366);
            break;
        }

        if (btnSortBy != null) {
          btnSortBy.Label = labelSort;
          btnSortBy.IsAscending = _guiSortAsc;
        }
      }
    }

    #region List/View Mutation

    private void selectListItemWithKey(string key) {
      Predicate<GUIListItem> predicate = delegate(GUIListItem item) {
        return item.Path == key;
      };
      trailerBrowser.SelectedListItemIndex = _listItems.FindIndex(predicate);
    }

    private void filterListItems() {
      Predicate<GUIListItem> predicate = delegate(GUIListItem item) {
        return (Common.Utils.NumPadEncode(item.Label).Contains(_listFilter) || item.IsFolder);
      };
      List<GUIListItem> filteredList;

      if (String.IsNullOrEmpty(_listFilter)) {
        filteredList = _listItems;
        Log.Debug("Browse Filter OFF", _listFilter);
      }
      else {
        filteredList = _listItems.FindAll(predicate);
        Log.Info("Browse Filter ON: '{0}'", _listFilter);
      }

      updateTrailerBrowser(filteredList);
      updateGuiState();
    }

    private void updateTrailerBrowser() {
      updateTrailerBrowser(_listItems);
    }

    private void updateTrailerBrowser(List<GUIListItem> items) {

      // Clear the trailerBrowser control (facade)
      GUIControl.ClearControl(GetID, trailerBrowser.GetID);
      // trailerBrowser.Clear();
      // trailerBrowser.ListView.TextColor = 0xffa0d0ff;

      // Add the items
      foreach (GUIListItem item in items)
        trailerBrowser.Add(item);

      // Set the item count
      _guiLabelItemcount = trailerBrowser.Count;
      if (_guiLabelItemcount > 0) {
        // select the first item
        trailerBrowser.SelectedListItemIndex = 0;
        // if the first item in the list is actually a "back" folder
        // decrement the item count 
        if (trailerBrowser[0].Label == "..")
          _guiLabelItemcount--;
      }
      // Update the GUI State
      updateGuiState();
    }

    private void clearFocus() {
      if (trailerBrowser != null) {
        trailerBrowser.Focus = false;
        if (trailerBrowser.ListView != null) trailerBrowser.ListView.Focus = false;
        if (trailerBrowser.ThumbnailView != null) trailerBrowser.ThumbnailView.Focus = false;
        if (trailerBrowser.FilmstripView != null) trailerBrowser.FilmstripView.Focus = false;
      }
      if (videoBrowser != null) videoBrowser.Focus = false;
      if (btnSortBy != null) btnSortBy.Focus = false;
      if (btnViewAs != null) btnViewAs.Focus = false;
      if (btnRefresh != null) btnRefresh.Focus = false;
    }

    #endregion

    private void SetProperty(string property, string value) {
      // If the added value is empty always add a space
      // otherwise the property will keep it's old value
      if (String.IsNullOrEmpty(value))
        value = "";

      GUIPropertyManager.SetProperty(property, value);
      //Log.Info("[My Trailers] SetProperty: {0} = {1}", tag, tagvalue);
    }

    private bool OnClickPrevious() {
      // if the first item in the list is not selected don't bother
      if (trailerBrowser.SelectedListItemIndex != 0)
        return false;

      // go back
      showPrevious();
      return true;
    }

    private void onChangeFacadeView() {
      switch (_guiView) {
        case View.List:
          this._guiView = View.Icons;
          break;
        case View.Icons:
          this._guiView = View.LargeIcons;
          break;
        case View.LargeIcons:
          this._guiView = View.FilmStrip;
          break;
        case View.FilmStrip:
          this._guiView = View.List;
          break;
      }
      SwitchView();
    }

    private void SwitchView() {
      if (trailerBrowser == null)
        return;

      string strLine = String.Empty;
      switch (_guiView) {
        case View.List:
          trailerBrowser.View = GUIFacadeControl.ViewMode.List;
          strLine = GUILocalizeStrings.Get(101);
          break;
        case View.Icons:
          trailerBrowser.View = GUIFacadeControl.ViewMode.SmallIcons;
          strLine = GUILocalizeStrings.Get(100);
          break;
        case View.LargeIcons:
          trailerBrowser.View = GUIFacadeControl.ViewMode.LargeIcons;
          strLine = GUILocalizeStrings.Get(417);
          break;
        case View.FilmStrip:
          trailerBrowser.View = GUIFacadeControl.ViewMode.Filmstrip;
          strLine = GUILocalizeStrings.Get(733);
          break;
      }

      GUIControl.SetControlLabel(GetID, btnViewAs.GetID, strLine);
    }

    private void OnVideoSelected(GUIListItem item, GUIControl parent) {
      Video video = item.AlbumInfoTag as Video;
      if (video != null) {
        SetProperty("#MyTrailers.Video.Title", video.Label);
        SetProperty("#MyTrailers.Video.Image", video.Thumb);
        SetProperty("#MyTrailers.Video.Description", video.Description);
        SetProperty("#MyTrailers.Video.Published", video.Date.ToShortDateString());
        //SetProperty("#MyTrailers.Video.Quality", video.Size);
      }
      else {
        SetProperty("#MyTrailers.Video.Title", "");
        SetProperty("#MyTrailers.Video.Image", "");
        SetProperty("#MyTrailers.Video.Description", "");
        SetProperty("#MyTrailers.Video.Published", "");
        //SetProperty("#MyTrailers.Video.Quality", "");
      }
    }

    private void OnItemSelected(GUIListItem item, GUIControl parent) {
      //#MyTrailers.List.Cover
      if (!item.IsFolder) {
        if (_guiState == State.Details) {
          trailerBrowser.FilmstripView.InfoImageFileName = _selectedTrailer.Poster;
        }
        else {
          Trailer trailer = item.AlbumInfoTag as Trailer;
          //OnTrailerSelectedExposeLabels(trailer);
          trailerBrowser.FilmstripView.InfoImageFileName = trailer.Poster;
        }
      }
    }

    private void OnShowDialogSelectVideo() {
      _selectedVideo = _selectedTrailer.Media[videoBrowser.SelectedListItem.Path];

      if (_selectedVideo.Size.Count > 1) {
        // only show dialog if the users has a choice
        GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
        if (dlg == null) return;
        dlg.Reset();
        dlg.SetHeading("Choose your quality"); // Sort options
        foreach (VideoQuality q in _selectedVideo.Size.Keys) {
          dlg.Add(videoQualityToString(q));
        }

        // show dialog and wait for result
        dlg.DoModal(GetID);
        if (dlg.SelectedId == -1) return;

        _selectedVideoSize = stringToVideoQuality(dlg.SelectedLabelText);
      }
      else {
        // select the only size available
        foreach (VideoQuality q in _selectedVideo.Size.Keys) {
          _selectedVideoSize = q;
        }
      }


      // Play selected trailer
      PlayTrailer();
    }

    #region Sort (based on GUIVideoBaseWindow)

    private void OnSortChanged(object sender, SortEventArgs e) {
      _guiSortAsc = e.Order != SortOrder.Descending;
      OnSort();
      GUIControl.FocusControl(GetID, ((GUIControl)sender).GetID);
    }

    private void OnSort() {
      //SetLabels();
      trailerBrowser.Sort(new GUIListItemTrailerComparer(_guiSortMethod, _guiSortAsc));
      updateGuiButtons();
    }

    private void OnShowDialogSortOptions() {
      GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
      if (dlg == null) return;
      dlg.Reset();
      dlg.SetHeading(495); // Sort options

      dlg.AddLocalizedString(268); // title
      dlg.Add("Sort By: Release Date"); // release date (need to localize this)

      // set the focus to currently used sort method
      dlg.SelectedLabel = (int)_guiSortMethod;

      // show dialog and wait for result
      dlg.DoModal(GetID);
      if (dlg.SelectedId == -1) return;

      switch (dlg.SelectedLabel) {
        case 1:
          _guiSortMethod = GUIListItemTrailerComparer.SortMethod.ReleaseDate;
          break;
        default:
          _guiSortMethod = GUIListItemTrailerComparer.SortMethod.Title;
          break;
      }

      OnSort();
      GUIControl.FocusControl(GetID, btnSortBy.GetID);
    }

    #endregion

    public void PlayTrailer() {
      bool playOk = false;
      string url = _selectedVideo.Size[_selectedVideoSize].OriginalString;

      _playingTrailer = true;

      Log.Info("[MyTrailers] Trying PlayStream()", url);
      // By Directshow Merit System
      playOk = g_Player.PlayVideoStream(url, _selectedTrailer.Title);
      if (!playOk) {
        // Fallback (Will only work for External Player)
        Log.Info("[MyTrailers] Trying Play()", url);
        playOk = g_Player.Play(url, g_Player.MediaType.Video);
      }

      // if ok go fullscreen
      if (playOk) {
        Log.Info("[MyTrailers] Playback OK.", url);
        g_Player.ShowFullScreenWindow();
        g_Player.FullScreen = true;
      }
      else {
        Log.Info("[MyTrailers] Unable to play {0}", url);
        GUIDialogNotify dlg = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
        dlg.SetHeading("ERROR");
        dlg.SetText("Unable to play the selected video trailer. Please try again later.");
        dlg.DoModal(GUIWindowManager.ActiveWindow);
      }

    }

    private void onShowDialogNoData() {
      GUIDialogNotify dlg = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
      dlg.SetHeading("ERROR");
      dlg.SetText("No data available. Please try again later.");
      dlg.DoModal(GUIWindowManager.ActiveWindow);
    }

    #region Playback Info

    private void OnPlayBackStarted(g_Player.MediaType type, string filename) {
      //Log.Info("[MyTrailers] OnPlayBackStarted");
      if (_selectedTrailer != null && _playingTrailer) {
        //Log.Info("[MyTrailers] Thread Start UpdatePlaybackInfo");
        Thread newThread = new Thread(new ThreadStart(UpdatePlaybackInfo));
        newThread.Start();
      }
    }

    private void OnPlayBackEnded(g_Player.MediaType type, string filename) {
      //Log.Info("[MyTrailers] OnPlayBackEnded");
      _playingTrailer = false;
    }

    private void UpdatePlaybackInfo() {
      Thread.Sleep(2000);
      //Log.Info("[MyTrailers] UpdatePlaybackInfo");
      if (_selectedTrailer != null) {
        SetProperty("#Play.Current.Title", _selectedTrailer.Title + " - " + _selectedVideo.Label + " (" + videoQualityToString(_selectedVideoSize) + ")");
        SetProperty("#Play.Current.Genre", _selectedTrailer.Genres.ToString());
        SetProperty("#Play.Current.Plot", _selectedTrailer.Description);
        SetProperty("#Play.Current.Thumb", _selectedTrailer.Poster);
        SetProperty("#Play.Current.Year", _selectedTrailer.Year.ToString());
        SetProperty("#Play.Current.Director", _selectedTrailer.Director);
        SetProperty("#Play.Current.Cast", _selectedTrailer.Cast.ToString());
      }
    }

    #endregion

    // there are more easier ways to do this, rewrite this eventually
    private static string videoQualityToString(VideoQuality q) {
      switch (q) {
        case VideoQuality.HD:
          return "HD";
        case VideoQuality.SD:
          return "SD";
        case VideoQuality.FULLHD:
          return "HD 1080P";
        case VideoQuality.HD720:
          return "HD 720P";
        case VideoQuality.HD480:
          return "HD 480P";
        case VideoQuality.LARGE:
          return "Large";
        case VideoQuality.MEDIUM:
          return "Medium";
        case VideoQuality.SMALL:
          return "Small";
        default:
          return "Unknown";
      }
    }
    private static VideoQuality stringToVideoQuality(string label) {
      switch (label) {
        case "HD":
          return VideoQuality.HD;
        case "SD":
          return VideoQuality.SD;
        case "HD 1080P":
          return VideoQuality.FULLHD;
        case "HD 720P":
          return VideoQuality.HD720;
        case "HD 480P":
          return VideoQuality.HD480;
        case "Large":
          return VideoQuality.LARGE;
        case "Medium":
          return VideoQuality.MEDIUM;
        case "Small":
          return VideoQuality.SMALL;
        default:
          return VideoQuality.UNKNOWN;
      }
    }

    // TO IMPLEMENT 

    protected bool GetKeyboard(ref string strLine) {
      VirtualKeyboard keyboard = (VirtualKeyboard)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_VIRTUAL_KEYBOARD);
      if (null == keyboard)
        return false;
      keyboard.Reset();
      keyboard.Text = strLine;
      keyboard.DoModal(GetID);
      if (keyboard.IsConfirmed) {
        strLine = keyboard.Text;
        return true;
      }
      return false;
    }

    public GUITrailers() {
      g_Player.PlayBackStarted += new g_Player.StartedHandler(OnPlayBackStarted);
      g_Player.PlayBackEnded += new g_Player.EndedHandler(OnPlayBackEnded);
    }

  }
}
